package com.hb.commons;

import cn.hutool.core.util.ArrayUtil;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import redis.clients.jedis.JedisPool;

import java.util.concurrent.TimeUnit;

/**
 * Redis操作公共类
 *
 * @param <K> Redis存储键, 通常情况下为字符串
 * @param <V>
 *
 * @author zhaojk
 */
public abstract class AbstractRedisService<K, V> {

    protected RedisTemplate<K, V> redisTemplate;

    protected AbstractRedisService(RedisTemplate<K, V> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 切换数据库
     *
     * @param num
     */
    public synchronized void setDataBase(int num) {
        LettuceConnectionFactory connectionFactory = (LettuceConnectionFactory) redisTemplate.getConnectionFactory();
        if (connectionFactory == null) {
            return;
        }
        int _num = connectionFactory.getDatabase();
        if (_num == num) {
            return;
        }
        connectionFactory.setDatabase(num);
        connectionFactory.afterPropertiesSet(); // 需要调用此方法进行链接的初始化, 否则setDataBase不生效
        this.redisTemplate.setConnectionFactory(connectionFactory);
        connectionFactory.resetConnection();
    }

    /**
     * 指定缓存失效时间
     *
     * @param key  键
     * @param time 时间(豪秒)
     *
     * @return
     */
    public boolean expire(K key, long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.MILLISECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 删除指定的键值
     *
     * @param keys
     */
    public boolean delete(K... keys) {
        if (ArrayUtil.isEmpty(keys)) {
            return false;
        }
        for (K key : keys) {
            if (key != null && key.toString().trim().length() > 0) {
                redisTemplate.delete(keys[0]);
            }
        }
        return true;
    }
}
